package com.siqi.hr.system.custom.controller;

import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.common.model.ModuleType;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.service.EntityRecordService;
import com.siqi.hr.system.exception.DeleteException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 实体注册信息控制层
 * @author    xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Controller
@RequestMapping("EntityRecord")
public class EntityRecordController {
    private static final Logger logger = Logger.getLogger(EntityRecordController.class);

    @Autowired
    private EntityRecordService entityRecordService;

    /**
     * 初始化系统设置对象管理页面
     * @author         xiaogq
     * @param request
     * @return
     */
    @RequestMapping(value = "initEntity", method = RequestMethod.GET)
    public ModelAndView initEntity(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        EntityOperation operation = new EntityOperation("新建自定义对象","addEntity","EntityRecord/entityRecordAddInit.do","image/common/operation/oper_ADD.png", OperationEnum.showList.name(),new EntityRecord(0));
        List<EntityOperation> listButtons = new ArrayList<EntityOperation>();
        listButtons.add(operation);
        //得到系统设置对象管理列头
        Map<String, Object> columnMap = entityRecordService.queryEntityListColumns();
        mav.addObject("listButtons",listButtons);
        mav.addObject("columns",columnMap.get("columns"));
        mav.addObject("entity", new EntityRecord(0,"自定义对象"));
        mav.setViewName("system/custom/entity/entity_list");
        return mav;
    }

    /**
     * 查询所有的系统对象或者自定义对象
     * @author         xiaogq
     * @param request
     * @param systemEntity  查询系统对象还是自定义对象标识(1:系统对象，0：自定义对象)
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "queryEntityList")
    @ResponseBody
    public Map<String,Object> queryEntityList(HttpServletRequest request, Boolean systemEntity) throws Exception {
        boolean isysEntity = systemEntity == null ? true : systemEntity;
        //得到系统设置对象管理数据
        Map<String,Object> resultMap = entityRecordService.queryEntityData(isysEntity);
        return resultMap;
    }

    /**
     * 布局管理列表页面
     * @author         xiaogq
     * @param request
     * @return
     */
    @RequestMapping(value = "initEntityLayoutList", method = RequestMethod.GET)
    public ModelAndView initEntityLayoutList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        //得到系统设置布局管理列头
        Map<String,Object> columnMap = entityRecordService.queryEntityListColumns();
        mav.addObject("columns",columnMap.get("columns"));
        mav.addObject("tableCode", 0);
        mav.addObject("title", "实体");
        mav.setViewName("system/custom/entity/entitylayout_list");
        return mav;
    }

    /**
     * 查询系统设置模块中布局管理列表数据
     * @author         xiaogq
     * @param request
     * @param systemEntity
     * @return
     * @throws IOException
     */
    @RequestMapping("queryEntityLayoutList")
    @ResponseBody
    public Map<String, Object> queryEntityLayoutList(HttpServletRequest request, Boolean systemEntity) throws Exception {
        boolean isysEntity = systemEntity == null ? true : systemEntity;
        Map<String,Object> dataMap = this.entityRecordService.queryEntityLayoutData(isysEntity);
        return dataMap;
    }

    /**
     * 添加自定义实体对象
     * @author         xiaogq
     * @return
     */
    @RequestMapping(value = "entityRecordAddInit", method = RequestMethod.GET)
    public ModelAndView entityRecordAddInit() {
        return new ModelAndView("system/custom/entity/entity_add");
    }

    /**
     * 实体编辑
     * @author         xiaogq
     * @param entityId       实体id
     * @return
     */
    @RequestMapping(value = "entityRecordUpdateInit", method = RequestMethod.GET)
    public ModelAndView entityRecordUpdateInit(Integer entityId) throws Exception{
        EntityRecord entity = this.entityRecordService.queryEntityRecordById(entityId);
        //处理所属模块
        String mudule = entity.getBelongMudule();
        String last1thStr = null;
        if (mudule != null) {
            char[] chars = mudule.toCharArray();
            last1thStr = chars[1]+"";
        }
        ModelAndView andView = new ModelAndView();
        andView.addObject("entity", entity);
        andView.addObject("last1thStr", last1thStr);
        andView.setViewName("system/custom/entity/entity_edit");
        return andView;
    }

    /**
     * 添加自定义实体保存方法
     * @author         xiaogq
     * @param entity    实体信息对象
     * @Return ModelAndView
     */
    @RequestMapping(value="entityRecordAdd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> entityRecordAdd(HttpServletRequest request,EntityRecord entity) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        //模块处理---start---
        String[] belongMudules = request.getParameterValues("belongMudule");
        StringBuffer moduleMark = new StringBuffer();
        if(null != belongMudules && belongMudules.length > 0){
            for(int i = 1; i < ModuleType.values().length+1; i++){
                moduleMark.append( Arrays.asList(belongMudules).contains(i+"") ? "1" : "0" );
            }
        }else{
            moduleMark.append(ModuleType.NO_MODULE);
        }
        entity.setBelongMudule(moduleMark.toString());
        //模块处理---end---
        //根据不同的条件创建自定义实体
        int counts = entityRecordService.addEntityRecord(entity);
        if(counts > 0){
            map.put("results","success");
        }else{
            map.put("results","error");
        }
        return map;
    }

    /**
     * 保存编辑实体方法
     * @param request
     * @param entity    实体对象信息
     * @throws Exception
     */
    @RequestMapping(value = "entityRecordEdit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> entityRecordEdit(HttpServletRequest request,EntityRecord entity) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        //修改实体信息
        int counts = entityRecordService.updateEntityRecord(entity);
        if (counts > 0){
            map.put("results","success");
        }else{
            map.put("results","error");
        }
        return map;
    }

    /**
     * 删除自定义实体通用方法
     * @author         xiaogq
     * @param request
     * @param entityId  要删除的实体Id
     * @throws Exception
     */
    @RequestMapping(value = "entityRecordDelete", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> entityRecordDelete(HttpServletRequest request,Integer entityId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            this.entityRecordService.deleteEntityRecord(entityId);
            map.put("info", "success");
        } catch (DeleteException e1) {
            map.put("info", "表中有数据");
        } catch (RuntimeException e) {
            map.put("info", "error");
        }
        return map;
    }

}
